package com.dxyxx.framework;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.type.JavaType;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dxyxx.R;
import com.dxyxx.dialog.AgainPlayer;
import com.dxyxx.pojo.Category;
import com.http.HttpUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * ActivityGroup装载子Activity，注意，装载完了之后会调用子Activity的onDestory方法，
 * 如果子Activity是FragmentActivity，那么肯定会报错"Activity has been destoryed"。为什么，自己想。
 * 
 * 
 * @author chinesejie
 * 
 */
public class CategoryFragment extends BaseFragment {
	private ViewPager vp;
	private int statusBarHeight;
	private int itemHeight;
	private int height;
	private float density;
	//private ViewGroup viewContainer;
	private View view;
	private String urlString;
	private ImageView[] imagesIndex;
	private ViewGroup indexLayout;
	private ImageView index0;
	private ImageView refreshImage;
	private Animation anim;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		//viewContainer = (ViewGroup) inflater.inflate(R.layout.fragment_wait, container, false);
		// 真实内容
		view = inflater.inflate(R.layout.activity_category, container, false);

		/**
		 * 计算常量
		 */
		DisplayMetrics metric = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
		height = metric.heightPixels; // 屏幕高度（像素）
		density = metric.density; // 屏幕密度（0.75 / 1.0 / 1.5）
		statusBarHeight = getStatusBarHeight();
		itemHeight = (int) ((height - (50 + 65) * density - statusBarHeight) / 3.0);
		initViews(view);

		callNetwork();
		return view;
	}

	// oncreate 中 可以运行，得到状态栏高度
	public int getStatusBarHeight() {
		int result = 0;
		int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
		if (resourceId > 0) {
			result = getResources().getDimensionPixelSize(resourceId);
		}
		return result;
	}

	public void initViews(View view) {
		//		((ImageView) view.findViewById(R.id.backImageButton)).setVisibility(View.INVISIBLE);
		((ImageView) view.findViewById(R.id.nextImageButton)).setVisibility(View.INVISIBLE);
		((TextView) view.findViewById(R.id.title)).setText("品类");
		indexLayout = (ViewGroup) view.findViewById(R.id.indexLayout);
		index0 = (ImageView) view.findViewById(R.id.index0);
		vp = (ViewPager) view.findViewById(R.id.vp_core_multi_controller);
		refreshImage = (ImageView) view.findViewById(R.id.backImageButton);
		refreshImage.setImageResource(R.drawable.refresh_normal);
		anim = AnimationUtils.loadAnimation(getActivity(), R.anim.round_loading);
		refreshImage.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				callNetwork();
			}
		});
	}

	private ViewHolder holder = null; // 如果缓存convertView为空，则需要创建View

	public class GridAdapter extends BaseAdapter {
		private Context mContext;
		private String[] images;
		private String[] texts;
		private long[] ids;
		private LayoutInflater mInflater;

		public GridAdapter(Context c, long[] ids, String[] images, String[] texts) {
			this.mInflater = LayoutInflater.from(c);
			mContext = c;
			this.ids = ids;
			this.images = images;
			this.texts = texts;
		}

		@Override
		public int getCount() {
			return texts.length;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {
			holder = null;
			if (convertView == null) {// 如果缓存convertView为空，则需要创建View
				holder = new ViewHolder();
				// 根据自定义的Item布局加载布局
				convertView = mInflater.inflate(R.layout.core_grid_item, null);
				LinearLayout rl = (LinearLayout) convertView.findViewById(R.id.relaGrid);
				rl.setLayoutParams(new GridView.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, itemHeight));
				holder.text = (TextView) convertView.findViewById(R.id.chooseText);
				holder.image = (ImageView) convertView.findViewById(R.id.chooseImage);
				convertView.setTag(holder);
			}
			holder = (ViewHolder) convertView.getTag();
			holder.text.setText(texts[position]);
			imageLoader.displayImage(images[position], holder.image, squareOptions, animateFirstListener);
			convertView.setOnClickListener(new ClickListener(ids[position] + "", texts[position]));
			return convertView;
		}

		//		@Override
		//		public View getView(int position, View convertView, ViewGroup arg2) {
		//			View view = View.inflate(mContext, R.layout.core_grid_item, null);
		//			LinearLayout rl = (LinearLayout) view.findViewById(R.id.relaGrid);
		//			// 设置每个item的高度 需要进行计算的。。
		//			// ( 整个屏幕的高度-（50+65）*dpi )/3
		//			rl.setLayoutParams(new GridView.LayoutParams(android.view.ViewGroup.LayoutParams.FILL_PARENT, itemHeight));
		//			ImageView imageView = (ImageView) rl.findViewById(R.id.chooseImage);
		//			TextView text = (TextView) rl.findViewById(R.id.chooseText);
		//
		//			// image.setImageResource(R.drawable.core_homepage_received_scan);
		//			imageLoader.displayImage(images[position], imageView, squareOptions, animateFirstListener);
		//
		//			text.setText(texts[position]);
		//			
		//			rl.setOnClickListener(new ClickListener(ids[position] + "", texts[position]));
		//			return rl;
		//		}
		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
	}

	static class ViewHolder {

		public TextView text;
		public ImageView image;

	}

	class ClickListener implements OnClickListener {
		private String id;
		private String name;

		public ClickListener(String id, String name) {
			this.id = id;
			this.name = name;
		}

		@Override
		public void onClick(View arg0) {
			// startActivity(new Intent(getActivity(),
			// ProductActivity.class));
			FragmentTransaction transaction = getFragmentManager().beginTransaction();
			// Replace whatever is in thefragment_container view with
			// this fragment,
			// and add the transaction to the backstack
			ProductFragment fragment = new ProductFragment();
			Bundle bundle = new Bundle();
			bundle.putString("categoryId", id);
			bundle.putString("categoryName", name);
			fragment.setArguments(bundle);
			transaction.add(R.id.categoryLayoutS, fragment);// 切记，categoryLayoutS这个name 在app中必须全局唯一，不然会有问题。
			// 提交修改
			transaction.commitAllowingStateLoss();
		}
	}

	// 导航图标变化
	class PageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageSelected(int arg0) {
			for (ImageView im : imagesIndex) {
				im.setImageResource(R.drawable.core_multi_unselected);
			}
			imagesIndex[arg0].setImageResource(R.drawable.core_multi_selected);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}
	};

	private void callNetwork() {
		refreshImage.startAnimation(anim);
		refreshImage.setClickable(false);// 禁止重复发送。
		urlString = "category/list";
		HttpUtil.get(urlString, new AsyncHttpResponseHandler() {

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				refreshImage.setClickable(true);
				AgainPlayer againPlayer = new AgainPlayer(getActivity(), new com.dxyxx.dialog.AgainPlayer.CallBack() {

					@Override
					public void method() {
						callNetwork();
					}
				});
				againPlayer.call("貌似没网了！");
				refreshImage.clearAnimation();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				refreshImage.setClickable(true);
				try {
					JavaType type = getObjectMapper().getTypeFactory().constructCollectionType(List.class, Category.class);
					List<Category> categories = getObjectMapper().readValue(new String(arg2), type);
					int size = categories.size() / 9;
					int more = categories.size() % 9;

					String[][] images = new String[size][9];
					String[][] texts = new String[size][9];
					long[][] ids = new long[size][9];

					for (int i = 0; i < size; i++) {
						for (int j = 0; j < 9; j++) {
							if (i * 9 + j < categories.size()) {
								texts[i][j] = categories.get(i * 9 + j).getDescription();
								images[i][j] = baseImageURL + categories.get(i * 9 + j).getImageId() + "?p=0";
								ids[i][j] = categories.get(i * 9 + j).getId();
							} else {
								break;
							}
						}
					}
					List<View> list = new ArrayList<View>();

					for (int i = 0; i < size; i++) {
						LayoutInflater mInflater = LayoutInflater.from(getActivity());
						View fragment1 = mInflater.inflate(R.layout.core_fragment1, null);
						GridView gridView1 = (GridView) fragment1.findViewById(R.id.gv_core_fragment1_gridView);
						gridView1.setAdapter(new GridAdapter(getActivity(), ids[i], images[i], texts[i]));
						list.add(fragment1);
					}
					if (more > 0) {
						String[] moreImages = new String[more];
						String[] moreTexts = new String[more];
						long[] moreIds = new long[more];

						for (int j = 0; j < 9; j++) {
							if (size * 9 + j < categories.size()) {
								moreTexts[j] = categories.get(size * 9 + j).getDescription();
								moreImages[j] = baseImageURL + categories.get(size * 9 + j).getImageId() + "?p=0";
								moreIds[j] = categories.get(size * 9 + j).getId();
							} else {
								break;
							}
						}

						LayoutInflater mInflater = LayoutInflater.from(getActivity());
						View fragment1 = mInflater.inflate(R.layout.core_fragment1, null);
						GridView gridView1 = (GridView) fragment1.findViewById(R.id.gv_core_fragment1_gridView);
						gridView1.setAdapter(new GridAdapter(getActivity(), moreIds, moreImages, moreTexts));
						list.add(fragment1);
					}
					vp.setAdapter(new ViewPagerAdapter(list));
					vp.setOnPageChangeListener(new PageChangeListener());
					// 指示标杆
					if (more > 0) {
						size++;
					}
					imagesIndex = new ImageView[size];
					imagesIndex[0] = index0;
					index0.setImageResource(R.drawable.core_multi_selected);
					indexLayout.removeAllViews();//删除所有子view
					indexLayout.addView(index0);
					for (int i = 1; i < size; i++) {
						imagesIndex[i] = new ImageView(getActivity());
						LinearLayout.LayoutParams ll = (LinearLayout.LayoutParams) index0.getLayoutParams();
						imagesIndex[i].setLayoutParams(ll);
						imagesIndex[i].setImageResource(R.drawable.core_multi_unselected);
						indexLayout.addView(imagesIndex[i]);
					}

				} catch (JsonParseException e) {
					e.printStackTrace();
				} catch (JsonMappingException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					refreshImage.clearAnimation();
				}

			}
		});
	}

}
